import os
import pymysql
from dotenv import load_dotenv

# 加载环境变量
load_dotenv()

def setup_database():
    """设置数据库和初始表结构"""
    print("正在初始化数据库...")
    
    # 连接数据库
    conn = pymysql.connect(
        host=os.getenv('MYSQL_HOST', 'localhost'),
        port=int(os.getenv('MYSQL_PORT', 3307)),
        user=os.getenv('MYSQL_USER', 'root'),
        password=os.getenv('MYSQL_PASSWORD', '123456'),
        charset='utf8mb4',
        cursorclass=pymysql.cursors.DictCursor
    )
    
    try:
        with conn.cursor() as cursor:
            # 读取SQL脚本
            with open('init_db.sql', 'r', encoding='utf-8') as f:
                sql_script = f.read()
            
            # 执行SQL脚本（按语句分割）
            for statement in sql_script.split(';'):
                if statement.strip():
                    cursor.execute(statement + ';')
            
            conn.commit()
            print("数据库初始化成功！")
    except Exception as e:
        print(f"初始化数据库时出错: {e}")
    finally:
        conn.close()

if __name__ == "__main__":
    setup_database()
    print("您现在可以使用以下信息登录：")
    print("用户名: test")
    print("密码: password123") 